package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppCertificate;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppCertificateService;
import com.byit.service.IAppNewsService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName appCertificateController
 * @Description 证件管理
 * @Author lxp
 * @Date 2019-01-07 11:38
 **/
@RestController
@RequestMapping("/api/sys/appCertificate")
public class AppCertificateController {


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppCertificateService appCertificateService;

    @Autowired
    private IAppNewsService appNewsService;

    /**
     * nginx代理url
     */
    @Value("${minio.searchMinio}")
    private String searchMinio;

    /**
     * 新增或修改证件管理信息
     *
     * @param session
     * @param appCertificate
     * @return
     */
    @PostMapping("/add")
    @Log(title = "证件管理", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    public Object insertAnnouncement(HttpSession session, AppCertificate appCertificate) {


        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == appCertificate) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }

            appCertificate.setCreateTime(new Date());
            appCertificate.setUpdateTime(new Date());
            // 加密用户密码
            appCertificate.setOperationId(userId);
            appCertificate.setUserId(userId);

            appCertificateService.insertOrUpdate(appCertificate);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }


    /**
     * 修改证件管理信息
     *
     * @param session
     * @param appCertificate
     * @return
     */
    @PostMapping("/edit")
    @Log(title = "证件管理", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object editAppCertificate(HttpSession session, AppCertificate appCertificate) {


        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == appCertificate) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (appCertificate.getId() != 0) {

                appCertificate.setUpdateTime(new Date());
            }
            //// 加密用户密码
            appCertificate.setOperationId(userId);

            appCertificateService.insertOrUpdate(appCertificate);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 通过Id查询证件管理
     *
     * @param id
     * @return
     */
    @GetMapping("/details")
    @Log(title = "证件管理", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppNewsById(@RequestParam("id") Integer id) {
        AppCertificate appCertificate = appCertificateService.selectById(id);
        return MessageResult.success(appCertificate);
    }


    /**
     * 按照条件查询证件管理
     *
     * @param session
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    @Log(title = "证件管理", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppNewsAll(HttpSession session,
                                   @RequestParam(value = "type", defaultValue = "") String type,
                                   @RequestParam(value = "name", defaultValue = "") String name,
                                   @RequestParam(value = "isCheck", defaultValue = "") String isCheck,
                                   @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                   @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppCertificate> pageInfo = new Page<>(page, limit);
        Map<String, Object> params = MapBuilder.newMap(5)
                .setParam("type", type)
                .setParam("isCheck", isCheck)
                .ok();
        if (null != name && !"".equals(name)) {
            params.put("name", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(name) + "%");
        }
        Page<JSONObject> result = appCertificateService.selectAppCertificateAll(pageInfo, params);

        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 逻辑删除证件管理信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/del")
    @Log(title = "证件管理", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    public Object delAppNewsByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();

        for (Long id : idList) {
            map.put("id", id);
            appCertificateService.delAppCertificateById(map);
        }
        return MessageResult.success();
    }


    /**
     * 证件审核
     *
     * @param id
     * @return
     */
    @PostMapping("/check")
    @Log(title = "证件管理", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object publishAppCertificate(@RequestParam("id") Long id,
                                        @RequestParam("check") Integer check) {
        AppCertificate info = appCertificateService.selectById(id);
        info.setUpdateTime(new Date());
        info.setId(id);
        info.setIsCheck(check);
      /*  EntityWrapper<AppCertificate> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id,picture,url,title,priority,by_order as byOrder");
        wrapper.eq("is_del", 0);
        // if (StringUtil.isNotNull(appBanner.getPriority())){
        wrapper.eq("id", id);
        wrapper.eq("check", check);*/
        try {

            appCertificateService.updateById(info);
        } catch (Exception e) {
            return MessageResult.error(e.getMessage());
        }

        return MessageResult.success();
    }


}
